package cn.stylefeng.guns.modular.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.system.entity.DealerLevel;
import cn.stylefeng.guns.modular.system.entity.IndentOrder;
import cn.stylefeng.guns.modular.system.entity.IndentOrderCheck;
import cn.stylefeng.guns.modular.system.entity.PurchaseOrders;
import cn.stylefeng.guns.modular.system.mapper.IndentOrderMapper;
import cn.stylefeng.guns.modular.system.mapper.PurchaseOrdersMapper;
import cn.stylefeng.guns.modular.system.model.params.PurchaseOrdersParam;
import cn.stylefeng.guns.modular.system.model.result.PurchaseOrdersResult;
import cn.stylefeng.guns.modular.system.service.DealerLevelService;
import cn.stylefeng.guns.modular.system.service.IndentOrderCheckService;
import cn.stylefeng.guns.modular.system.service.IndentOrderService;
import cn.stylefeng.guns.modular.system.service.PurchaseOrdersService;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.util.utility.Order;
import cn.stylefeng.guns.sys.core.util.utility.StatusCode;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.aspectj.lang.annotation.SuppressAjWarnings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 订货单表 服务实现类
 * </p>
 *
 * @author 飞
 * @since 2019-07-02
 */
@Service
public class PurchaseOrdersServiceImpl extends ServiceImpl<PurchaseOrdersMapper, PurchaseOrders> implements PurchaseOrdersService {


    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;
    @Autowired
    private IndentOrderService indentOrderService;
    @Autowired
    private IndentOrderCheckService indentOrderCheckService;
    @Autowired
    private DealerLevelService dealerLevelService;


    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;
    @Resource
    private TaskService taskService;


    @Override
    public void add(PurchaseOrdersParam param) {
        PurchaseOrders entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public ResponseData submit(List<PurchaseOrdersParam> purchaseOrdersParams) {

        PurchaseOrders purchaseOrders = null;
        StringBuilder stringBuilder = new StringBuilder();
        for (PurchaseOrdersParam purchaseOrdersParam : purchaseOrdersParams) {
            BigDecimal orderAmount = null;
            purchaseOrders = new PurchaseOrders();
            //遍历插入每条数据到 采购单表中
            BeanUtil.copyProperties(purchaseOrdersParam, purchaseOrders);
            //判断是否为最大单位
            if (purchaseOrdersParam.getUnitMin() == purchaseOrdersParam.getUnitId()) {
                orderAmount = purchaseOrdersParam.getOrderNumbers().multiply(purchaseOrdersParam.getPrice()).setScale(2);
                purchaseOrders.setOrderAmount(orderAmount);
            } else if (purchaseOrdersParam.getUnitMax() == purchaseOrdersParam.getUnitId()) {
                orderAmount = purchaseOrdersParam.getOrderNumbers().multiply(purchaseOrdersParam.getPrice()).multiply(purchaseOrdersParam.getConversionRatio()).setScale(2);
                purchaseOrders.setOrderAmount(orderAmount);
            }
            purchaseOrders.setRemark(purchaseOrdersParam.getRemark());
            purchaseOrders.setHavaSend(new BigDecimal(StatusCode.DEFAULTVALUE.getVal()));
            purchaseOrders.setNotSend(purchaseOrdersParam.getOrderNumbers());
            purchaseOrders.setHavaSendPrice(new BigDecimal(0.0));
            purchaseOrders.setNotSendPrice(orderAmount);
            purchaseOrders.setStatus(StatusCode.DOING.getVal());
            purchaseOrdersMapper.insert(purchaseOrders);

            //找出最新的数据
            PurchaseOrders purchaseOrdersLast = purchaseOrdersMapper.selectOne(new QueryWrapper<PurchaseOrders>()
                    .orderByDesc("purchase_id").last("limit 1"));
            stringBuilder.append(purchaseOrdersLast.getPurchaseId() + ",");
        }

        IndentOrder indentOrder = new IndentOrder();
        indentOrder.setCheckCode(StatusCode.PENDING.getVal());
        indentOrder.setDealer(ShiroKit.getUserNotNull().getId());
        indentOrder.setPurchaseId(stringBuilder.toString());
        indentOrder.setTime(new DateTime());

        //获取编号
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        StringBuilder builder = new StringBuilder();
        builder.append(Order.NM_);
        int year = calendar.get(Calendar.YEAR);
        builder.append(year);
        Integer month = calendar.get(Calendar.MONTH);
        builder.append(month);
        Integer day = calendar.get(Calendar.DATE);
        builder.append(day);
        IndentOrder indentOrderLast = indentOrderService.getOne(new QueryWrapper<IndentOrder>()
                .orderByDesc("id").last("limit 1"));
        if (ToolUtil.isEmpty(indentOrderLast)) {
            builder.append((long) 1);
        } else {
            builder.append(indentOrderLast.getId() + 1);
        }
        indentOrder.setIndentOrderNum(builder.toString());
//        //同时更新数据到订货单审核表中
//        IndentOrderCheck indentOrderCheck = new IndentOrderCheck();
//        //找到刚插入的订货表
//        IndentOrder indentOrderNew = indentOrderService.getOne(new QueryWrapper<IndentOrder>()
//                .orderByDesc("id").last("limit 1"));
//        indentOrderCheck.setIndetOrderId(indentOrderNew.getId());
//        indentOrderCheck.setStatus(StatusCode.PENDING.getVal());
//                /*indentOrderCheck.setAddressId(dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
//                        .eq("sys_user_id",ShiroKit.getUserNotNull().getDeptId())).getAreaId());*/
//        indentOrderCheckService.save(indentOrderCheck);
//
//        return ResponseData.success(200, "添加成功", purchaseOrdersParams);
        identityService.setAuthenticatedUserId(ShiroKit.getUserNotNull().getId() + "");
        //启动流程实例，字符串"vacation"是BPMN模型文件里process元素的id
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("pc_indent_order");
        indentOrder.setProcessInstanceId(processInstance.getId());
        indentOrderService.save(indentOrder);
        //流程实例启动后，流程会跳转到经销商提交
        Task vacationApply = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        //设置经销商提交任务的执行人
        taskService.setAssignee(vacationApply.getId(), ShiroKit.getUserNotNull().getId() + "");
        //完成经销商提交任务
        taskService.complete(vacationApply.getId());

        return  ResponseData.success(200,"添加成功",purchaseOrdersParams);
    }

    @Override
    public void delete(PurchaseOrdersParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(PurchaseOrdersParam param) {
        PurchaseOrders oldEntity = getOldEntity(param);
        PurchaseOrders newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public PurchaseOrdersResult findBySpec(PurchaseOrdersParam param) {
        return null;
    }

    @Override
    public List<PurchaseOrdersResult> findListBySpec(PurchaseOrdersParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(PurchaseOrdersParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(PurchaseOrdersParam param) {
        return param.getPurchaseId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private PurchaseOrders getOldEntity(PurchaseOrdersParam param) {
        return this.getById(getKey(param));
    }

    private PurchaseOrders getEntity(PurchaseOrdersParam param) {
        PurchaseOrders entity = new PurchaseOrders();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
